package com.ds.common.org.expression.personduty;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.*;
import com.ds.server.OrgManagerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Stack;

/**
 * 取得指定人员具有的人员职务
 * <p>
 * Title: JDSORG组织机构中间件
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: jds Copyright (c) 2003-2008
 * </p>
 * <p>
 * Company: www.justdos.net
 * </p>
 *
 * @author wenzhangli
 * @version 2.0
 */
public class GetPersonDutyByPerson extends Function {
    public GetPersonDutyByPerson() {
        numberOfParameters = 1;
    }

    public void run(Stack stack) throws ParseException {
        checkStack(stack); // check the stack

        Object param2 = stack.pop();
        stack.push(perform(param2));
    }

    protected Role[] perform(Object param1) throws ParseException {
        if (param1 == null) {
            return new Role[0];
        }
        // 人员的标识
        if (param1 instanceof String) {
            String personId = (String) param1;
            List<Role> duties = new ArrayList<Role>();
            OrgManager orgManager = OrgManagerFactory.getOrgManager();
            try {
                Person person = orgManager.getPersonByID(personId);
                if (person != null) {
                    Set<String> roles = person.getRoleIdList();
                   for (String roleId : roles) {
                        Role role = null;
                        try {
                            role = orgManager.getRoleByID(roleId);
                        } catch (RoleNotFoundException e) {
                            e.printStackTrace();
                        }
                        if (role != null && role.getType().equals(RoleType.Duty)) {
                            duties.add(role);
                        }
                    }

                    return (Role[]) duties.toArray();
                }
                return new Role[0];
            } catch (PersonNotFoundException e) {
                return new Role[0];
            }
        }
        // 人员对象
        if (param1 instanceof Person) {
            return perform(((Person) param1).getID());
        }
        throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
    }
}